package com.mybook.app.service;

import com.mybook.app.core.UserContext;
import com.mybook.app.mapper.WalletInfoMapper;
import com.mybook.app.mapper.WtInfoMapper;
import com.mybook.app.model.WalletInfo;
import com.mybook.app.model.WtInfo;
import com.mybook.app.renum.PayTypeEnum;
import com.mybook.app.utils.IdUtils;
import com.mybook.app.utils.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by zjutsw on 2017/11/10.
 */
@Service
public class WalletService {

    @Autowired
    private WalletInfoMapper walletInfoMapper;

    @Autowired
    private WtInfoMapper wtInfoMapper;
    @Autowired
    private UserService userService;

    /**
     * 获取我的钱包
     */
    public WalletInfo walletInfo() {
        WalletInfo walletInfo = walletInfoMapper.findWalletInfoById(UserContext.getCurrentuserId().get());
        if (null == walletInfo) {
            walletInfo = new WalletInfo();
            walletInfo.setId(UserContext.getCurrentuserId().get());
            walletInfo.settValue(new BigDecimal(0));
            walletInfo.setuValue(new BigDecimal(0));
            int row = walletInfoMapper.insertSelective(walletInfo);
            Logger.info(this, "不存在用户钱包，插入数据 ：" + row);
        }
        return walletInfo;
    }

    /**
     * 保存支付流水
     *
     * @param bId         书籍id
     * @param oId         对方id
     * @param uId         操作者id
     * @param tId         流水id
     * @param payTypeEnum 支付类型
     */
    public void saveWtInfo(String bId, String oId, String uId, String tId, PayTypeEnum payTypeEnum, BigDecimal value) {
        String city = userService.getCity();
        String id = IdUtils.getId(city);
        WtInfo wtInfo = new WtInfo();
        wtInfo.setId(id);
        wtInfo.setbId(bId);
        wtInfo.setoId(oId);
        wtInfo.setuId(uId);
        wtInfo.settId(tId);
        wtInfo.setValue(value);
        wtInfo.setTime(new Date());
        wtInfo.setType(payTypeEnum.getValue());
        int row = wtInfoMapper.insertSelective(wtInfo);
        Logger.info(this, "插入流水 ：" + row);
    }


    /**
     * 支付
     *
     * @param payMoney 支付金额
     * @param userId   用户id
     * @param oId      对方id
     * @param bId      书籍id
     * @param tId      流水id
     */
    public void payWt(BigDecimal payMoney, String userId, String oId, String bId, String tId) {
        // 支付
        Integer row = walletInfoMapper.payWalletInfoById(payMoney, userId);
        Logger.info(this, "支付 ：" + row);
        //日志
        saveWtInfo(bId, oId, userId, tId, PayTypeEnum.rental_payment, payMoney);
        //收益
        Integer row1 = walletInfoMapper.incomeWalletInfoById(payMoney, oId);
        Logger.info(this, "收益：" + row1);
        //日志
        saveWtInfo(bId, userId, oId, tId, PayTypeEnum.income, payMoney);
    }


}
